package com.bsh.repository;

import com.bsh.api.ApiUtils;
import com.bsh.mybatis.IRepository.SysConfigMapper;
import com.bsh.mybatis.model.SysConfig;
import com.bsh.utils.Pager;
import com.bsh.utils.RedisUtil;
import com.bsh.utils.SimpleCache;
import com.mysql.jdbc.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Repository
public class DaoSysConfig {
    private static Logger log = LoggerFactory.getLogger(DaoSysConfig.class);

    private static Integer cacheTime = 60 * 60 * 24;

    private static SimpleCache<Integer> cache = new SimpleCache<Integer>(cacheTime);

    RedisUtil ru = null;

    @Resource
    SqlSessionTemplate session;

    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedJdbcTemplate;

    @Autowired
    HttpServletRequest request;

    SysConfigMapper getMapper() {
        return session.getMapper(SysConfigMapper.class);
    }

    public int deleteByPrimaryKey(Integer id) {
        int res = getMapper().deleteByPrimaryKey(id);
        return res;
    }

    public int insert(SysConfig record) {
        int res = getMapper().insert(record);
        return record.getId();
    }

    public int insertSelective(SysConfig record) {
        int res = getMapper().insertSelective(record);
        return record.getId();
    }

    public SysConfig selectByPrimaryKey(Integer id) {
        SysConfig row = getMapper().selectByPrimaryKey(id);
        return row;
    }

    public int updateByPrimaryKeySelective(SysConfig record) {
        int res = getMapper().updateByPrimaryKeySelective(record);
        return res;
    }

    public int updateByPrimaryKey(SysConfig record) {
        int res = getMapper().updateByPrimaryKey(record);
        return res;
    }

    public int updateByPrimaryKeyWithBLOBs(SysConfig record) {
        int res = getMapper().updateByPrimaryKeyWithBLOBs(record);
        if (res > 0) {
            try {
                Integer value = Integer.parseInt(record.getSvalue());
                cache.Put(record.getSkey(), value);
            } catch (NumberFormatException e) {
                log.info("修改app配置不需要加缓存");
            }
        }
        return res;
    }

    /**
     * 查询IOS版本信息
     *
     * @return
     */
    public List<SysConfig> getIOSVersionConfig() {
        return this.getMapper().getIOSVersionConfig();
    }

    /**
     * 查询ANDROID版本信息
     *
     * @return
     */
    public List<SysConfig> getANDROIDVersionConfig() {
        return this.getMapper().getANDROIDVersionConfig();
    }

    /**
     * App配置分页
     */
    public List<Map<String, Object>> getAppPage(Pager pager, String where) {
        StringBuilder sb = new StringBuilder();
        MapSqlParameterSource ps = new MapSqlParameterSource();
        sb.append("SELECT * from sys_config ");
        sb.append("where (skey like 'ios_%') or (skey like 'and_%') ");
        if (!StringUtils.isNullOrEmpty(where)) {
            sb.append(where);
        }
        Integer count = namedJdbcTemplate.queryForInt("select count(0) from (" + sb.toString() + ")v", ps);

        sb.append(" order by id asc limit :start,:size");
        ps.addValue("start", pager.getStart());
        ps.addValue("size", pager.getPageSize());
        List<Map<String, Object>> list = namedJdbcTemplate.queryForList(sb.toString(), ps);

        pager.setRowCount(count);
        return list;
    }

    /**
     * 系统配置分页
     */
    public List<Map<String, Object>> getSysPage(Pager pager, String where) {
        StringBuilder sb = new StringBuilder();
        MapSqlParameterSource ps = new MapSqlParameterSource();
        sb.append("SELECT * from sys_config ");
        sb.append("where (skey not like 'ios_%') and (skey not like 'and_%') ");
        if (!StringUtils.isNullOrEmpty(where)) {
            sb.append(where);
        }
        Integer count = namedJdbcTemplate.queryForInt("select count(0) from (" + sb.toString() + ")v", ps);

        sb.append(" order by id asc limit :start,:size");
        ps.addValue("start", pager.getStart());
        ps.addValue("size", pager.getPageSize());
        List<Map<String, Object>> list = namedJdbcTemplate.queryForList(sb.toString(), ps);

        pager.setRowCount(count);
        return list;
    }

    /**
     * 意见反馈
     *
     * @param userid
     * @param feedBack
     */
    public void appendFeedback(String userName, String feedBack) {
        String sql = "INSERT INTO `feedback` (	`mobile`,`feedback`) VALUES	('" + userName + "', '" + feedBack + "') ";
        jdbcTemplate.execute(sql);
    }

//	/**
//	 * 查询每日注册量
//	 * 
//	 * @return
//	 */
//	public Integer getIpMaxIPRegDaily() {
//		StringBuilder sb = new StringBuilder();
//		sb.append("SELECT svalue from sys_config ");
//		sb.append("where skey like '%max_ip_reg_daily%' limit 1");
//		Integer result = null;
//		try {
//			result = jdbcTemplate.queryForInt(sb.toString());
//		} catch (DataAccessException e) {
//			return result;
//		}
//		return result;
//	}
//
//	/**
//	 * 查询每日最大分享商币限额
//	 *
//	 * @return
//	 */
//	public Integer getMaxShareCloud() {
//		StringBuilder sb = new StringBuilder();
//		sb.append("SELECT svalue from sys_config ");
//		sb.append("where skey like '%max_share_cloud%' limit 1");
//		Integer result = null;
//		try {
//			result = jdbcTemplate.queryForInt(sb.toString());
//		} catch (DataAccessException e) {
//			return result;
//		}
//		return result;
//	}
//
//	
//
//	/**
//	 * 查询当天累计充值限额
//	 *
//	 * @return
//	 */
//	public Integer getDayRechargeLimit() {
//		StringBuilder sb = new StringBuilder();
//		sb.append("SELECT svalue from sys_config ");
//		sb.append("where skey like '%day_recharge_limit%' limit 1");
//		Integer result = null;
//		try {
//			result = jdbcTemplate.queryForInt(sb.toString());
//		} catch (DataAccessException e) {
//			return result;
//		}
//		return result;
//	}
//
//	/**
//	 * 查询ip分享限制
//	 *
//	 * @return
//	 */
//	public Integer getDayIpShareLimit() {
//		StringBuilder sb = new StringBuilder();
//		sb.append("SELECT svalue from sys_config ");
//		sb.append("where skey like '%day_ip_share_cloud_limit%' limit 1");
//		Integer result = null;
//		try {
//			result = jdbcTemplate.queryForInt(sb.toString());
//		} catch (DataAccessException e) {
//			return result;
//		}
//		return result;
//	}

    /**
     * 查询系统配置
     * 先查缓存，缓存有直接返回，缓存没有就查数据库，并放入缓存
     *
     * @param key
     * @return
     */
    public Integer findSysKey(String key) {
        StringBuilder sb = new StringBuilder();
        Integer result = null;
        result = cache.Get(key, Integer.class);
        if (ApiUtils.objIsEmpty(result)) {
            sb.append("SELECT svalue from sys_config ");
            sb.append("where skey like '%" + key + "%' limit 1");
            try {
                result = jdbcTemplate.queryForInt(sb.toString());
            } catch (DataAccessException e) {
                log.error("查询" + key + "失败" + e.getMessage());
                return result;
            }
            if (ApiUtils.objIsNotEmpty(result)) {
                cache.Put(key, result);
            }

        }
        return result;
    }

}
